function! Gcc()
    let filename = expand('%')
	let root = 'a'
    let makeprg  = 'set makeprg=gcc\ -Wall\ -o' . root . '\ ' . filename
    silent! exe makeprg
    silent! exe ':update'

    silent! exe 'make'

    call HideOutput()
    call Quickfix()
endfunction

function! Quickfix()
    let list = getqflist()
    let bugs = len(list)

    if bugs == 0
        echo 'Compile success!'
        " Hide the quickfix window
        silent! exe 'cw'
        call Run()
    else
        echo 'Fix bugs first.'
        " Show the quickfix window
        silent! exe 'cw ' . string((bugs + 1) > 9 ? 9 : (bugs + 1))
    endif
endfunction

function! HideOutput()
    let output_file = string(getpid()) . '.output'
    let bufnumlist  = tabpagebuflist()

    for bufnum in bufnumlist
        let file = bufname(bufnum)
        if file =~# output_file 
            silent! exe string(bufnum) . ' bwipe!' 
            break
        endif
    endfor

    silent! exe ':setlocal laststatus=2'
endfunction

function! Run()
    call HideOutput()
    
    let src_winnr   = winnr()
    let output_file = string(getpid()) . '.output'
	let bin_file = 'a'

    if executable(bin_file) != 1
        " Program not exist
        echo bin_file . '.exe not exist.'
        return
    endif

    redir => sb_message
    silent! set sb?
    redir END
    let sb_message = 'set '. substitute(sb_message, '^\W\s*', '', '')

    :set splitbelow
    silent! exe '6split ' . output_file 
    silent! exe '%!' . bin_file

    "silent! exe ':update'
    silent! exe ':set filetype=tmp'
    silent! exe ':setlocal laststatus=0'
    :set nosplitbelow

    silent! set sb_message
    silent! exe src_winnr . 'wincmd w'
endfunction

autocmd FileType c,cpp  nnoremap <buffer><silent> ,g  :call Gcc()<cr>
autocmd FileType c,cpp  nnoremap <buffer><silent> ,r  :call Run()<cr>
autocmd FileType c,cpp  nnoremap <buffer><silent> ,h  :call HideOutput()<cr>
autocmd FileType tmp    nnoremap <buffer><silent> ,h  :call HideOutput()<cr>
